import java.util.Calendar;

import javax.swing.JOptionPane;

/**
 * control class for shopping cart window
 */

public class CartControl
{
	/** array of strings, used to send data in to the sever */
	public String[] query;
	/** array of strings, used to show the books in the reader's shopping cart */
	public String[] res;
	/** flag indicating if the membership bought by the reader is yearly or monthly */
	public boolean isYearly;
	/** Gui class for choosing membership type */
	ChooseMemberShipGUI mem=null;
	/** holds the information about the reader's membership */
	public String[] str=new String[2];
	/** sums the total price of the books purchased */
	public Integer sum=0;
	
	/** initialize class variables */
	public CartControl(){}
	
	/** retrieves all of the books in the user's shopping cart.
	 * this method also eliminates books in the shopping cart, that were removed
	 * from the catalog and are now unavailable for purchase
	 * @return String[][]
	 */
	public String[][] g_retrieve()
	{
		String temp;
		String[] err;
		String[][] data=null;
		query=new String[3];
		query[0]=Main.gusers.id;
		query[1]="retrieve_cart";
		query[2]=Main.gusers.id;
		Main.log.connection.accept("cart");
		while(Main.log.flag==false);
		Main.log.flag=false;
		temp=ChatClient.getRs();
		err=temp.split("\\%");
		if(err.length==0)
			res=null;
		else
		{	
			res=err[0].split("\\*");
			if(res[0].equals(""))
				res=null;
			else
			{
				data=new String[res.length][4];
				for(int i=0;i<res.length;i++)
					data[i]=res[i].split("\\#");
			}
		}
		String[] date;
		Main.cart.query=new String[3];
		Main.cart.query[0]=Main.gusers.id;
		Main.cart.query[1]="checkMembership_MembershipBuy";
		Main.cart.query[2]=Main.gusers.id;
		Main.log.connection.accept("cart");
		while(Main.log.flag==false);
		Main.log.flag=false;
		temp=ChatClient.getRs();
		date=temp.split("\\.");
		if(date[0].equals("valid"))
		{
			str[0]="Memberhip Expiration:";
			str[1]="          "+date[1]+"."+date[2]+"."+date[3];
		}
		else if(date[0].equals("expMembership"))
		{
			str[0]="Your Memberhip";
			str[1]="Have Expired";
		}
		else
		{
			str[0]="You Don't Have";
			str[1]="a Membership";
		}
		if(err.length>1)
			if(err[1].length()>0)
				JOptionPane.showMessageDialog(null,err[1]+" Was Removed From The Catalog And Also From Your Cart","ERROR",JOptionPane.ERROR_MESSAGE);
		return data;
		
	}
	
	/** this method is used to buy a membership, the reader can either buy yearly or monthly membership */
	public void g_buyWithMembership()
	{
		String temp;
		if(!(Main.cartgui.jTable.getRowCount()==0))
		{
			temp=Main.cartgui.memexp.getText();
			if(temp.equals("Have Expired")) JOptionPane.showMessageDialog(null,"Membership Expired","ERROR",JOptionPane.ERROR_MESSAGE);
			else if(temp.equals("a Membership")) JOptionPane.showMessageDialog(null,"You don't have a membership","ERROR",JOptionPane.ERROR_MESSAGE); 
			else valid(true);
		}
		else
			JOptionPane.showMessageDialog(null,"You Have no books in The Cart","ERROR",JOptionPane.ERROR_MESSAGE); 
	}
	
	/** this method is used to buy the books in the cart by credit card(isBuyBooks --> true)
	 * or is used to buy a membership(isBuyBooks --> false). 
	 * 
	 * @param isBuyBooks
	 */
	public void g_buywithCrditCard(boolean isBuyBooks)
	{
		if((!(Main.cartgui.jTable.getRowCount()==0)) || isBuyBooks==false)
		{
			CreditCardGui credit=new CreditCardGui(isBuyBooks);
			credit.setVisible(true);
		}
		else
			JOptionPane.showMessageDialog(null,"You Have no books in The Cart","ERROR",JOptionPane.ERROR_MESSAGE); 
	}
	
	/** this method is used to give the reader a choice between yearly or monthly membership */
	public void chooseMembership(boolean validationFlag)
	{
		if(validationFlag)
		{
			/** holds temporary information about the reader's membership */
			String temp;
			/** holds the expiration date of the current membership */
			String[] date;
			temp=Main.cartgui.memexp.getText();
			
			if(temp.equals("Have Expired") || temp.equals("a Membership"))
			{
				String[] todayDate=new String[4];
				Calendar cal = Calendar.getInstance(); 
				Integer month = cal.get(Calendar.MONTH) + 1; 
				Integer year = cal.get(Calendar.YEAR)%100; 
				Integer day=cal.get(Calendar.DAY_OF_MONTH);
				todayDate[0]=day.toString();
				todayDate[1]=month.toString();
				todayDate[2]=year.toString();
				if (temp.equals("Have Expired")) todayDate[3]="Have Expired";
				else todayDate[3]="a Membership";
				mem=new ChooseMemberShipGUI(Main.log.frame,todayDate);
				mem.setVisible(true);
			}
			else 
			{
				temp+=".valid";
				date=temp.split("\\.");
				temp=date[0];
				int i=0,j=0,k=0;
				i=temp.indexOf("1");
				j=temp.indexOf("2");
				k=temp.indexOf("3");
				if((i>j && j!=-1) || i==-1) i=j;
				if((i>k && k!=-1) || i==-1) i=k;
				date[0]=temp.substring(i);
				mem=new ChooseMemberShipGUI(Main.log.frame,date);
				mem.setVisible(true);
				
			}
		}
		else JOptionPane.showMessageDialog(null,"Credit Card Not Valid","ERROR",JOptionPane.ERROR_MESSAGE);
			
	}
	
	/** updates the membership expiration date */
	public void registerUpdatedMembership(String[] date)
	{
		if (mem!=null) mem.dispose();
		Integer day,month,year;
		String[][] rec=new String[1][2];
		query=new String[5];
		query[0]=Main.gusers.id;
		query[1]="update Membership";
		query[2]=Main.gusers.id;
		query[4]=date[3];
		if(isYearly)
		{
			year=Integer.parseInt(date[2])+1;
			date[2]=year.toString();
			query[3]=date[0]+"."+date[1]+"."+date[2];
			day=Integer.parseInt(date[0]);
			month=Integer.parseInt(date[1]);
			year=Integer.parseInt(date[2]);
			sum=1000;
			rec[0][0]="Yearly Membership";
			rec[0][1]="1000";
		}
		else
		{
			int no_of_days_in_month;
			day=Integer.parseInt(date[0]);
			month=Integer.parseInt(date[1]);
			year=Integer.parseInt(date[2]);
			if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)
				no_of_days_in_month=31;
			else if(month==4||month==6||month==9||month==11)
				no_of_days_in_month=30;
			else if(year%4==0) no_of_days_in_month=29;
			else no_of_days_in_month=28;
			day=30-(no_of_days_in_month-day);
			if(month==12) 
			{
					month=1;
					year++;
			}
			else month++;
			query[3]=day+"."+month+"."+year;
			sum=200;
			rec[0][0]="Monthly Membership";
			rec[0][1]="200";
		}
		str[0]="Memberhip Expiration:";
		str[1]="          "+day+"."+month+"."+year;
		Main.cartgui.memdetails.setText(str[0]);
		Main.cartgui.memexp.setText(str[1]);
		if(Main.cartgui.jTable.getRowCount()!=0)
			Main.cartgui.memberShip.setEnabled(true);
		Main.log.connection.accept("cart");
		while(Main.log.flag==false);
		Main.log.flag=false;
		ReceiptGui receipt=new ReceiptGui(Main.log.frame,rec);
		receipt.setVisible(true);
	}
	
	/** after credit card or membership validation, this method is used for the actual purchase, and update of the databse */
	public void valid(boolean validationFlag)
	{
		if(validationFlag)
		{
			/** hold the number of books in cart */
			int rows=Main.cartgui.jTable.getRowCount();
			/** holds information for the books information table */
			String[][] rec;
			/** holds the prices for each book */
			String[] prices;
			/** holds a list of books purchased by the reader */
			String[] err = null;
			/** holds temporary result from the server */
			String temp;
			/** holds a list of books that were removed from the catalog before purchase, and therefore were unavailable for purchase */
			String outList ="";
			query=new String[5];
			query[0]=Main.gusers.id;
			query[1]="purchase";
			query[2]=Main.gusers.id;
			query[3]="";
			query[4]="";
			for(int i=0;i<rows;i++)
				query[3]+= Main.cartgui.jTable.getValueAt(i, 0)+"*";
			for(int i=0;i<rows;i++)
				query[4]+= Main.cartgui.jTable.getValueAt(i, 1)+"*";
			Main.log.connection.accept("cart");
			while(Main.log.flag==false);
			Main.log.flag=false;
			temp=ChatClient.getRs();
			err=temp.split("\\*");
			rec=new String[err.length][2];
			
			Main.cartgui.memberShip.setEnabled(false);
			Main.cartgui.creditCard.setEnabled(false);
			Main.cartgui.remove.setEnabled(false);
			prices=new String[rows];
			for(int i=0;i<rows;i++)
				prices[i]= (String) Main.cartgui.jTable.getValueAt(i, 3);
			sum=0;
			int j=0;
			
			for(int i=0;i<prices.length;i++)
			{
				
				if(temp.contains((CharSequence) Main.cartgui.jTable.getValueAt(i, 0)))
				{
					rec[j][0]=(String)  Main.cartgui.jTable.getValueAt(i, 0);
					rec[j][1]=prices[i];
					sum+=Integer.parseInt(prices[i]);
					j++;
				}
				else
				{
					outList+=Main.cartgui.jTable.getValueAt(i, 0)+" , ";
				}
			}
			if(outList.length()>0)
				JOptionPane.showMessageDialog(null,outList+"Was Removed From The Catalog And Also From Your Cart","ERROR",JOptionPane.ERROR_MESSAGE);
			if(j>0)
			{
				ReceiptGui receipt=new ReceiptGui(Main.log.frame,rec);
				receipt.setVisible(true);
			}
			else
				JOptionPane.showMessageDialog(null,"No Book Was Purchased","ERROR",JOptionPane.ERROR_MESSAGE);
			for(int i=0;i<rows;i++)
				Main.cartgui.model.removeRow(0);
			Main.cartgui.model.getDataVector().removeAllElements();
			Main.cartgui.panel.revalidate();
		}
		else JOptionPane.showMessageDialog(null,"Credit Card Not Valid","ERROR",JOptionPane.ERROR_MESSAGE);
	}
	
	/** method for navigation, goes back to the main screen */
	public void g_exit()
	{
		Main.cartgui.panel.setVisible(false);
		Main.cartgui.panel.setEnabled(false);
		if(Main.gusers.authorozations==1) Main.log.frame.setSize(450,320);
		else if(Main.gusers.authorozations==2) Main.log.frame.setSize(450,400);
		else if(Main.gusers.authorozations==3) Main.log.frame.setSize(450,515);
		Main.welcomeScreen.panel.setVisible(true);
		Main.welcomeScreen.panel.setEnabled(true);
	}
	
	/** removes a book from the user's cart */
	public void g_remove()
	{
		if(Main.cartgui.jTable.getSelectedRow()!=-1)
		{
			String bookName=(String) Main.cartgui.jTable.getValueAt(Main.cartgui.jTable.getSelectedRow(), 0);
			query=new String[4];
			query[0]=Main.gusers.id;
			query[1]="gremove";
			query[2]=Main.gusers.id;
			query[3]=bookName;
			Main.log.connection.accept("cart");
			while(Main.log.flag==false);
			Main.log.flag=false;
			if(bookName!=null)
			Main.cartgui.model.removeRow(Main.cartgui.jTable.getSelectedRow());
		}
		else JOptionPane.showMessageDialog(null,"You Didn't Select any Book","ERROR",JOptionPane.ERROR_MESSAGE);
	}
	/**
	 * logs out of the system
	 */
	public void exit()
	{
		Main.cartgui.panel.setVisible(false);
		Main.cartgui.panel.setEnabled(false);
		Main.log.loginData=new String[3]; //GIL
		Main.log.loginData[0]=Main.gusers.id;
		Main.log.loginData[1]="logout";
		Main.log.loginData[2]=Main.gusers.id;
		Main.log.connection.accept("logout"); //GIL
		Main.log.flag=false;//GIL
		while(Main.log.flag==false);//GIL
		Main.log.flag=false;//GIL
		Main.log.user.setText("");
		Main.log.pass.setText("");
		Main.log.frame.setSize(650,550);
		Main.log.panel.setEnabled(true);
		Main.log.panel.setVisible(true);
	}

}
